package com.zhn.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhn.shortlink.admin.common.biz.user.UserContext;
import com.zhn.shortlink.admin.common.convention.result.Result;
import com.zhn.shortlink.admin.dao.entity.GroupDO;
import com.zhn.shortlink.admin.dao.mapper.GroupMapper;
import com.zhn.shortlink.admin.dto.req.ShortLinkSortReqDTO;
import com.zhn.shortlink.admin.dto.req.ShortLinkUpdateReqDTO;
import com.zhn.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.zhn.shortlink.admin.remote.ShortLinkService;
import com.zhn.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.zhn.shortlink.admin.service.GroupService;
import com.zhn.shortlink.admin.toolkit.RandomGenerator;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 短链接分组接口实现层
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final ShortLinkService shortLinkService;

    /**
     * 新增短链接分组
     * @param groupName 分组名
     */
    @Override
    public void saveGroup(String groupName) {
        saveGroup(UserContext.getUsername(),groupName);
    }
    @Override
    public void saveGroup(String username,String groupName) {
        String gid ;
        do{
            gid = RandomGenerator.generateRandomString();
        }while (!hasGid(username,gid));
        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .name(groupName)
                .build();

        baseMapper.insert(groupDO);
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        // 从上下文获取用户名
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0)
                .orderByAsc(GroupDO::getSortOrder)
                .orderByAsc(GroupDO::getUpdateTime);
        List<GroupDO> groups = baseMapper.selectList(queryWrapper);
        List<ShortLinkGroupCountQueryRespDTO> gids = shortLinkService.listGroupShortLinkCount(groups.stream().map(GroupDO::getGid).toList()).getData();
        List<ShortLinkGroupRespDTO> results = BeanUtil.copyToList(groups, ShortLinkGroupRespDTO.class);
        Map<String, Long> counts = gids.stream().collect(Collectors.toMap(ShortLinkGroupCountQueryRespDTO::getGid, ShortLinkGroupCountQueryRespDTO::getShortLinkCount));
        return results.stream().peek(result -> result.setShortLinkCount(counts.get(result.getGid()))).toList();
    }

    @Override
    public void updateGroup(ShortLinkUpdateReqDTO requestParam) {
        LambdaQueryWrapper<GroupDO> updateWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO,updateWrapper);
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername,UserContext.getUsername())
                .eq(GroupDO::getDelFlag,0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO,queryWrapper);
    }

    @Override
    public void sortGroup(List<ShortLinkSortReqDTO> requestParam) {
        requestParam.forEach(e->{
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getDelFlag, 0)
                    .eq(GroupDO::getGid, e.getGid());
            GroupDO groupDO = GroupDO.builder().sortOrder(e.getSortOrder()).build();
            baseMapper.update(groupDO,queryWrapper);
        });
    }

    private boolean hasGid(String username,String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                // 设置用户名
                .eq(GroupDO::getId,gid)
                .eq(GroupDO::getUsername,Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO hasGroup = baseMapper.selectOne(queryWrapper);
        return hasGroup == null;
    }
}

